﻿@model AutoPartsSearch.Web.ViewModels.SellerSearchQuery.ViewModel
@using AutoPartsSearch.Web.HtmlHelpers
@{
    ViewBag.Title = @T("Список запросов").ToHtmlString();
}
<h2 class="title">@T("Список запросов")</h2>
<div class="container-main ui-corner-all padtop5 wid100prc">
    <div class="container-sub-no-width wid749px hght22px mrgbot3">
        <div class="fr">
            @T("Тип запросов"):
            <select id="listType" class="no-mrg-and-pad">
                <option value="null" selected="selected" data-url='@Url.Action("List")'>@T("Все")</option>
                <option value="false" data-url='@Url.Action("List", new { processed = false })'>@T("Необработанные")</option>
                <option value="true" data-url='@Url.Action("List", new { processed = true })'>@T("Обработанные")</option>
            </select>
        </div>
    </div>
    <div class="container-sub-no-width wid749px">
        <table id="list">
            <thead>
                <tr>
                    <th style="width: 100px;">
                    </th>
                    <th>
                        @T("Обработан")
                    </th>
                    <th>
                        @T("Запчасть")
                    </th>
                    <th>
                        @T("Группа")
                    </th>
                    <th>
                        @T("Брэнд")
                    </th>
                    <th>
                        @T("Модель")
                    </th>
                    <th>
                        @T("Год")
                    </th>
                    <th>
                        @T("Город")
                    </th>
                    <th style="width: 30px;"></th>
                </tr>
            </thead>
            <tbody>
                @foreach (var sellerSearchQuery in Model.SellerSearchQueries)
                {
                    <tr>
                        <td>
                            <div class="buttons ">
                                <div class="ui-state-default ui-corner-all  ui-icon-button">
                                    @Html.ActionLink(T("Детали").ToHtmlString(), "Details", new { id = sellerSearchQuery.SearchQuery.Id }, new { @class = "ui-icon ui-icon-search", title = @T("Детали запроса") })
                                </div>
                                <div class="ui-state-default ui-corner-all  ui-icon-button">
                                    @using (Html.BeginForm("Delete", "SellerSearchQuery", new { id = sellerSearchQuery.SearchQuery.Id }, FormMethod.Post))
                                    {
                                        <a href="#" class=" ui-icon ui-icon-trash delete dependable" title="@T("Удалить")">@T("Удалить")</a>
                                    }
                                </div>
                                <div class="ui-state-default ui-corner-all  ui-icon-button">
                                    @Html.ActionLink(T("Сделать предложение").ToHtmlString(), "SendOffer", "Offer", new { id = sellerSearchQuery.SearchQuery.Id }, new { @class = "ui-icon ui-icon-cart dependable", title = @T("Сделать предложение") })
                                </div>
                                
                            </div>
                        </td>
                        <td class="IsProcessed">
                            @(sellerSearchQuery.IsProcessed ? @T("Да") : @T("Нет"))
                        </td>
                        <td class="PartName">@sellerSearchQuery.SearchQuery.PartName
                        </td>
                        <td class="PartGroupName">@sellerSearchQuery.SearchQuery.PartGroup.Name.Default
                        </td>
                        <td class="CarBrandName">@sellerSearchQuery.SearchQuery.CarBrand.Name.Default
                        </td>
                        <td class="CarModel">@sellerSearchQuery.SearchQuery.CarModel
                        </td>
                        <td class="CarYear">@sellerSearchQuery.SearchQuery.CarYear
                        </td>
                        <td class="CityName">@sellerSearchQuery.SearchQuery.City.Name.Default
                        </td>
                        <td>
                            <div class="ui-state-default ui-corner-all  ui-icon-button">
                                    @Html.ActionLink(T("Котировки").ToHtmlString(), "History", "Offer", new { queryId = sellerSearchQuery.SearchQuery.Id }, new { @class = "ui-icon ui-icon-info quotes", title = @T("Котировки") })
                                </div>
                        </td>
                    </tr>
                }
            </tbody>
        </table>
    </div>
    <div class="container-sub mrgtop3 hght22px  wid749px">
        <div class="mrgtop3">
            @Html.PageLinks(Model.PagingInfo
                      , x => Url.Action("List", new { page = x, pageSize = Model.PagingInfo.ItemsPerPage, processed = ViewBag.Processed })
                      , "pagingLink ui-state-default ui-corner-all", "ui-state-active")
            @Html.ActionLink(@T("История моих предложений").ToHtmlString(), "Index", "Offer", null, new { @class = "fr bold" })
        </div>
    </div>
</div>
@section Scripts{
    <script type="text/javascript" language="javascript" src="~/Scripts/query.js"></script>
    <script type="text/javascript">
        

        $(document).ready(function () {
            
            

            $('.quotes').click(function (e) {
                e.preventDefault();
                var href = $(this).attr('href');
                $('<div id="dialog"></div>').appendTo('body'); 
                
                $('#dialog').dialog({
                    width: 400,
                    title: '@T("Котировки")',
                    modal: true,
                    resizable: false,
                    open: function (event, ui) {
                        $(this).load(href);
                    },
                    button: {
                        'Закрыть': function () {
                            $(this).dialog("close");
                        }
                    }
                });
            });

            var isBlocked = @ViewBag.IsSellerBlocked ;
            if (isBlocked) {
                $(".dependable").click(function (e) {
                    e.preventDefault();
                });
                $(".dependable").closest(".ui-icon-button").addClass("ui-state-disabled");
                $(".dependable").addClass("ui-state-disabled");
            }


            $(".buttons div").hover(
                function() {
                    $(this).addClass("ui-state-hover");
                },
                function() {
                    $(this).removeClass("ui-state-hover");
                });

            setListType();

            $("#listType").change(function() {
                var url = $("#listType option:selected").attr("data-url");
                window.location = url;
            });

            $(".delete").not(".ui-state-disabled").click(function() {
                if (confirm('@T("Вы действительно хотите удалить этот запрос из списка?")')) {
                    $(this).closest("form").submit();
                    return false;
                } else {
                    return false;
                }
            });

            var ajaxTimeOut = @AutoPartsSearch.Domain.Common.Constants.AjaxTimeout ;
            setTimeout(function () {hasNewRequest(ajaxTimeOut);} , ajaxTimeOut);
        });
        
        function setListType() {
            var processed = @ViewBag.Processed + "";
            $("#listType option[value='" + processed + "']").attr("selected", "selected");
        }
        
        function hasNewRequest(ajaxTimeOut){
            var url = "@Url.Action("HasNewRequests", "SellerSearchQuery")";
            $.ajax({
                url: url,
                dataType: 'json',
                type : 'GET',
                success: function (data) {
                    var hasNew = data;
                    if (hasNew) {
                        changeTitle();
                        updateUnprocessedCount();
                        addTheNewestRequest();
                    } else {
                        setTimeout(function () {hasNewRequest(ajaxTimeOut);} , ajaxTimeOut);
                    }
                },
                error: ajaxError
            });
        }
        
        function changeTitle() {
            var title = $(document).attr('title');
            if (title == '*************') {
                setTimeout(changeTitle, 500);
                $(document).attr('title', '@T("У Вас Новый запрос!!!")');
            }else {
                setTimeout(changeTitle, 500);
                $(document).attr('title', '*************');
            }
        }

        function updateUnprocessedCount() {
            var url = "@Url.Action("UnreadCount", "SellerSearchQuery")";
            $.ajax({
                url: url,
                dataType: 'json',
                type : 'GET',
                success: function (data) {
                    var count = data;
                    $('#unprocessedCount').text(count);
                    function blink() {
                        $('.unprocessed a').fadeOut().fadeIn();
                        setTimeout(blink, 1e3); 
                    };
                    blink();
                },
                error: ajaxError
            });
        }        
        
        function addTheNewestRequest() {
            var url = "@Url.Action("GetTheNewestItem", "SellerSearchQuery")";
            $.ajax({
                url: url,
                dataType: 'json',
                type : 'GET',
                success: function (data) {
                    var id = data.SearchQuery.Id;
                    var row = $('#list tbody tr:first').clone();
                    row.find('.IsProcessed').html('@T("Нет")');
                    row.find('.PartName').html(data.SearchQuery.PartName);
                    row.find('.PartGroupName').html(data.SearchQuery.PartGroup.Name.Default);
                    row.find('.CarBrandName').html(data.SearchQuery.CarBrand.Name.Default);
                    row.find('.CarModel').html(data.SearchQuery.CarModel);
                    row.find('.CarYear').html(data.SearchQuery.CarYear);
                    row.find('.CityName').html(data.SearchQuery.City.Name.Default);
                    row.find('.buttons>div>a').each(function() {
                        var href = $(this).attr('href');
                        $(this).attr('href', replaceUrl(href, id));
                    });
                    row.find('.buttons>div>form').each(function() {
                        var href = $(this).attr('action');
                        $(this).attr('action', replaceUrl(href, id));
                    });
                    $('#list tbody').prepend(row);
                    function blink() {
                        $('#list tbody tr:first').fadeOut().fadeIn();
                        setTimeout(blink, 1e3); 
                    };
                    blink();
                },
                error: ajaxError
            });
        }
        
        function replaceUrl(url, id) {
            var idx = url.lastIndexOf('/') + 1;
            return url.slice(0, idx) + id;
        }

    </script>
}
